//
//  ST_RankWebViewController.swift
//  btvideo
//
//  Created by Jason on 2021/7/23.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import WebKit
import SwiftyJSON
import WKWebViewJavascriptBridge


class ST_RankWebViewController: UIViewController,  WKNavigationDelegate {
    
    var webView = WKWebView()
    
    lazy var bridge = WKWebViewJavascriptBridge(webView: webView)
    
    private var urlStr:String = "http://rank.jingniaoapps.com"
    
    
    
    var titleStr = "排行榜"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print("排行榜 start:",Date())
        
        let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
        let date = Date(timeIntervalSince1970: 0)
        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })
        
        self.view.backgroundColor = Color.white
        webView.backgroundColor = Color.clear
        webView.isOpaque = false
        webView.navigationDelegate = self
        
        set_up_view()
        
        self.view.addSubview(webView)
        let line = UIView()
        line.backgroundColor = Color.init(hex: 0x999999, transparency: 0.3)
        self.view.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.top.equalTo(back_btn.snp.bottom).offset(5)
            make.left.right.equalTo(self.view)
            make.height.equalTo(1)
        }
        webView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.top.equalTo(line.snp.bottom)
        }
        
        bridge.register(handlerName: "NativeApi_popUserCenter") { (paramters, callback) in
            
            guard let p = paramters else{
                return
            }
            
            let pm = JSON(p)
            
            let accid = pm["accid"].stringValue
            
            
            let vc = ST_PairsCenterViewController()
            
            vc.accid = accid
            
            let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
            
            nav.overCurrentContext = true
            
            GlobalPresent(toController: nav)
            
            print("JS 查看用户主页:",pm)
            
        }
        
        
        bridge.register(handlerName: "NativeApi_popRankRule") { (paramters, callback) in
            
            //            let pm = JSON(paramters)
            //
            //            print("JS 查看Rank规则:",pm)
            
            let vc = ST_TrophyRulesViewController()
            
            vc.overCurrentContext = true
            
            GlobalPresent(toController: vc)
            
        }
        
        
        
        bridge.register(handlerName: "NativeApi_pullData") { (paramters, callback) in
            
            print("排行榜 first js call:",Date())
            
            guard let dict = paramters ,let jsCall = JSON.init(dictionary: dict) else {
                return
            }
            
            JVrequest(PH.getGiftRankByTypeApi,parameters: ["type":jsCall["type"].stringValue]) { (json) in
                
                //                print("排行榜后台返回数据json:",json);
                
                print("排行榜 api pulled success:",Date(),json)
                
                callback?(json.rawString() ?? "")
                
            } failure: { (code, err) in
                
                //                print("排行榜后台返回数据bug:",err);
                
                print("排行榜 api pulled failure:",Date(),"----",err)
                
                callback?("")
            }
        }
        
        
//        if let url = Bundle.main.url(forResource: "index", withExtension: "html"){
//            webView.loadFileURL(url, allowingReadAccessTo: url)
//        }
        
        if let url = URL.init(string: urlStr){
            webView.load(URLRequest(url: url))
        }
        
        
        
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    
    
    
    func set_up_view(){
        
        self.view.addSubview(navi_view)
        self.view.addSubview(back_btn)
        self.view.addSubview(titleLabel)
        self.view.addSubview(right_nav_btn)
        
        
        navi_view.snp.makeConstraints { (make ) in
            make.left.right.top.equalTo(self.view)
            
            make.height.equalTo(navigationBarHeight + statusBarHeight)
        }
        
        back_btn.snp.makeConstraints { (make ) in
            make.top.equalTo(self.view).offset(statusBarHeight)
            make.left.equalTo(self.view).offset(8)
            make.width.height.equalTo(44)
        }
        titleLabel.snp.makeConstraints { (make ) in
            make.centerY.equalTo(back_btn)
            make.centerX.equalTo(self.view)
            make.height.equalTo(25)
        }
        
        right_nav_btn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(back_btn)
            make.width.equalTo(68)
            make.height.equalTo(25)
        }
        
    }
    lazy var navi_view : UIView = {
        let view = UIView()
        view.backgroundColor = Color.white
        return view
    }()
    lazy var back_btn:UIButton = {
        let btn = UIButton()
        
        btn.setImageForAllStates(ST_ImageUtils.imageName("返回_gray")!)
        btn.addTarget(self, action: #selector(back_action(sender: )), for: .touchUpInside)
        return btn
    }()
    
    private lazy var right_nav_btn:UIButton = {
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(color: UIColor(hex: 0xFEC207)!, size: .init(width: 1, height: 1)), for: .normal)
        btn.setTitle("榜单奖励", for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 12, weight: .semibold)
        btn.setTitleColor(.white, for: .normal)
        btn.addTarget(self, action: #selector(right_btn_action(sender:)), for: .touchUpInside)
        btn.cornerRadius = 12
        return btn
    }()
    
    
    lazy var titleLabel:UILabel = {
        let control = UILabel()
        
        control.textColor = Color.black
        control.font = UIFont.systemFont(ofSize: 18)
        
        control.text = titleStr
        return control
    }()
    
    
    // MARK: - delegate
    //    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    //
    //        if let title = webView.title{
    //            self.titleLabel.text = title
    //        }
    //
    //    }
}

extension ST_RankWebViewController{
    
    @objc func back_action(sender: UIButton) {
        goback_previous_controller()
    }
    
    
    @objc func right_btn_action(sender: UIButton) {
        
        let vc = ST_BTWebViewController()
        
        vc.urlStr = "http://rank.jingniaoapps.com/rank_explain/"
        
        vc.titleStr = "榜单奖励"
        
        navigationController?.pushViewController(vc, animated: true)
    
    }
    
    
}

